/* eslint-disable camelcase */
import axios from 'axios';
import { FilterType } from '@/types/global';


export type Company = {
    id: number;
    name: string;
    short_name: string;
    legal_person: string;
    telephone: string;
    address: string;
    delivery_address: string;
    post_code: string;
    registered_capital: number;
    account: string;
    line_number: string;
    bank_name: string;
}

export function deleteCompany(id: number) {
  return axios.delete(`/api/company/${id}`)
}

export function transformCompany(company: any): Company {
  return {
      id: company.id,
      name: company.name,
      short_name: company.short_name,
      legal_person: company.legal_person,
      telephone: company.telephone,
      address: `${company.address}`,
      delivery_address: `${company.delivery_address}`,
      post_code: company.post_code,
      registered_capital: company.registered_capital,
      account: company.account,
      line_number: company.line_number,
      bank_name: company.bank_name
  };
}

export async function getAllCompany(page?: number, limit?: number, filter?: FilterType) {
  const keys = Object.keys(filter ?? {});
  const params = new URLSearchParams();
  params.set('page', page.toString());
  params.set('limit', limit.toString());
  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    const value = filter[key];
    if (value.type === 'enum') {
      if (Array.isArray(value.value) && value.value.length) {
        params.set(key, value.value.toString());
      }
    }
    if (value.type === 'input' && !Array.isArray(value.value)) {
      let sql = `${value.value.relation === 'contains' ? '%' : ''}${value.value.text}${value.value.relation === 'startwith' || value.value.relation === 'contains' ? '%' : ''}`;
      params.set(key, sql);
    }
  }
  // 调用接口获取公司数据
  const response = await axios.get(`/api/company?`);
  const originalCompanies = response.data;
  const formattedCompanies = originalCompanies.map(transformCompany);
  const responseData = {
      data: {
          meta: {
              totalItems: formattedCompanies.length,
          },
          items: formattedCompanies,
      },
  };
  return responseData;
}

export function getCompany(id: string) {
  return axios.get(`/api/company/info/${id}`);
}

export function updateCompany(data: any) {
  return axios.patch(`/api/company`, data);
}

export function addCompany(data: any) {
  return axios.post(`/api/company`, data);
}